package com.example.market_management.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.market_management.mapper.deliveryAddressMapper;
import com.example.market_management.model.DeliveryAddress;
import com.example.market_management.model.vo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("deliveryAddress")
@CrossOrigin
@Slf4j
public class deliveryAddressController {

    @Autowired
    private deliveryAddressMapper  deliveryAddressMapper;

    /**
     * 添加配送地址
     * @param userId
     * @param address
     * @param type
     * @return
     */
     @PostMapping("/addAddress")
     private CommonResult  addAddress(Integer userId,String address,Integer type){
           DeliveryAddress deliveryAddress=new DeliveryAddress();
           deliveryAddress.setUserId(userId);
           deliveryAddress.setAddress(address);
           deliveryAddress.setType(type);
           //如果设置当前地址为默认地址,则将原数据库中的默认地址设置为普通地址
           if(type==1)  deliveryAddressMapper.updateAddressType0(userId);
           int i=deliveryAddressMapper.insert(deliveryAddress);
           if(i==1) return CommonResult.success("添加配送地址成功");
           else  return CommonResult.success("添加配送地址失败");
      }

    /**
     * 更新默认地址
     * @param userId
     * @param addressId
     * @return
     */
      @PutMapping("/updateAddressType")
    private CommonResult  updateAddressType(Integer userId,Integer addressId){
          int i=deliveryAddressMapper.updateAddressType0(userId);
          log.info("更新了"+i+"条数据");
          int j= deliveryAddressMapper.updateAddressType1(addressId);
          if(j==1) return CommonResult.success("更新默认地址成功");
          else  return CommonResult.failed("更新失败");
      }

    /**
     * 更新配送地址
     * @param addressId
     * @param address
     * @return
     */
      @PutMapping("/updateAddress")
     private  CommonResult updateAddress(Integer addressId,String address){
         int i=deliveryAddressMapper.updateAddress(addressId,address);
         if(i==1) return CommonResult.success("更新配送地址成功");
         else  return CommonResult.failed("更新失败");
      }

    /**
     *查询当前用户的所有配送地址
     * @param userId
     * @return
     */
    @PostMapping("/addressList")
    private  CommonResult addressList(Integer userId){
          QueryWrapper queryWrapper=new QueryWrapper();
          queryWrapper.eq("user_id",userId);
          List<DeliveryAddress> deliveryAddressList=deliveryAddressMapper.selectList(queryWrapper);
          return CommonResult.success("查询订单列表成功",deliveryAddressList);

      }


}
